<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入采集名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['article:diySpider:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:diySpider:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:diySpider:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:diySpider:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-video-play"
          :loading="piLiangSpiderLoading"
          size="mini"
          @click="handleSpider"
          :disabled="multiple"
          v-hasPermi="['article:diySpider:add']"
        >批量采集</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList">

      </right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="diySpiderList" @update:data="handleDataUpdate" ref="myTable" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采集名称" align="center" prop="name" />
      <el-table-column label="来源" align="center" prop="itemName" />


      <el-table-column label="所属类目" align="center" prop="typeName" />
      <el-table-column label="图片目录" align="center" prop="savePath" />
      <el-table-column prop="status" label="状态" width="100">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
      </template>
    </el-table-column>
      <el-table-column prop="spiderStatus" label="采集状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.spider_status" :value="scope.row.spiderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-caret-right"
            :loading="scope.row.spiderLoading"
            @click="handleSpider(scope.row)"
            v-hasPermi="['article:diySpider:edit']"
          >执行采集</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['article:diySpider:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['article:diySpider:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采集配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" min-width="600px" append-to-body>
      <el-form ref="form" :model="form"  :inline="true" :rules="rules" label-width="80px">

        <el-form-item label="名称" prop="name" >
          <el-input v-model="form.name" placeholder="请输入采集名称" style="width: 240px"/>
        </el-form-item>

        <el-form-item label="主域名" prop="spiderDomain" >
          <el-input v-model="form.spiderDomain" placeholder="请输入主域名，用于鉴别网站" style="width: 240px"/>
        </el-form-item>

        <el-form-item label="采集来源" prop="itemId">
          <el-select v-model="form.itemId" ref="optionItemRef"  placeholder="请选择来源">
            <el-option
              v-for="item in itemOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="生成模型" prop="promptsId">
          <el-select v-model="form.promptsId" ref="optionPromtsRef"  placeholder="请选择模型">
            <el-option
              v-for="item in promptsOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="采集分类" prop="typeId">
          <treeselect style="width: 240px" ref="optionClassRef"  @select="addSelect" v-model="form.typeId" :options="spiderClassOptions" :show-count="true" placeholder="请选择归属分类" />
        </el-form-item>



        <el-form-item label="抓取列表地址" label-width="120px" prop="spiderUrl">
          <el-input v-model="form.spiderUrl" type="textarea" placeholder="请输入内容" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="列表标签" prop="listDiv">
          <el-input v-model="form.listDiv" placeholder="请输入列表标签" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="翻页标签" prop="pageDiv">
          <el-input v-model="form.pageDiv" placeholder="请输入翻页标签" style="width: 240px"/>
        </el-form-item>

        <el-form-item label="图片目录" prop="savePath">
          <el-input v-model="form.savePath" placeholder="请输入保存目录" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="排序" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入排序" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="删除div" prop="deleteDiv">
          <el-input v-model="form.deleteDiv" type="textarea" placeholder="需要删除的div 多个以;隔开，需带上元素#或者." style="width: 240px"/>
        </el-form-item>
        <el-form-item label="保留标签" prop="saveDiv">
          <el-input v-model="form.saveDiv" type="textarea" placeholder="请输入需要保留的标签 多个以;隔开，需带上元素#或者." style="width: 240px"/>
        </el-form-item>
        <el-form-item label="标题标签" prop="titleDiv">
          <el-input v-model="form.titleDiv" type="textarea" placeholder="请输入标题标签" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="时间标签" prop="pushTimeDiv">
          <el-input v-model="form.pushTimeDiv" type="textarea" placeholder="请输入发布时间标签" style="width: 240px"/>
        </el-form-item>
<!--        <el-form-item label="担任角色" prop="takeRole">-->
<!--          <el-input v-model="form.takeRole" type="textarea" placeholder="例如我希望你是一个家常菜美食家.." style="width: 240px"/>-->
<!--        </el-form-item>-->
<!--        <el-col :span="24">-->
<!--          <el-form-item label="生成风格" prop="genStyle">-->
<!--            <el-input v-model="form.genStyle" type="textarea"  :autosize="{ minRows: 10, maxRows: 12}" placeholder="请输入生成模板风格，防止大量生成同质化文章" style="width:580px;height: 240px"/>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { listDiySpider, getDiySpider, delDiySpider, addDiySpider, updateDiySpider,spiderItemSelect,spiderClassSelect,toSpider,PromptsSelect } from "@/api/article/diySpider";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "DiySpider",
  dicts: ['sys_normal_disable','spider_status'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      piLiangSpiderLoading:false,
      spiderLoading:false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采集配置表格数据
      diySpiderList: [],
      // 来源选项
      itemOptions: [],
      // 生成模型选项
      promptsOptions:[],
      //分类选项
      spiderClassOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemId: null,
        promptsId:null,
        name:null,
        itemName: null,
        status: null,
        spiderStatus:null,
        savePath: null,
        typeId: null,
        typeName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        itemId: [
          { required: true, message: "来源不能为空", trigger: "change" }
        ],
        typeId: [
          { required: true, message: "分类不能为空", trigger: "change" }
        ],
        spiderUrl: [
          { required: true, message: "采集地址不能为空", trigger: "blur" }
        ],
        promptsId: [
          { required: true, message: "生成模型不能为空", trigger: "change" }
        ],
        listDiv: [
          { required: true, message: "列表元素不能为空", trigger: "blur" }
        ],
        savePath: [
          { required: true, message: "素材保存目录不能为空", trigger: "blur" }
        ],
        titleDiv: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],

        orderId: [
          { required: true, message: "排序不能为空", trigger: "change" }
        ],
        saveDiv: [
          { required: true, message: "文章页面保存元素不能为空", trigger: "blur" }
        ],
        itemName: [
          { required: true, message: "来源名称不能为空", trigger: "change" }
        ],


        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();

  },
  mounted() {
  },
  methods: {
    /** 查询采集配置列表 */
    getList() {
      this.loading = true;
      listDiySpider(this.queryParams).then(response => {
        this.diySpiderList = response.rows;
        this.total = response.total;
        this.loading = false;
          this.$nextTick(() => {
            //处理按钮状态
            let datelists = this.diySpiderList;
            let isallspider = false;
            for(var i in datelists){
              let row = datelists[i];
              if(row.spiderStatus=="1"||row.spiderStatus=="3"){
                this.$set(row, 'spiderLoading', true);
                this.piLiangSpiderLoading = true;
                isallspider = true;
              }else{
                this.$set(row, 'spiderLoading', false);
              }
            }
            if(!isallspider){
              this.piLiangSpiderLoading = false;
            }else{
              this.piLiangSpiderLoading = true;
            }
          })
      });
    },
    handleDataUpdate(){


    },
    handleMyEvent(){
      console.log("时间...")
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        itemId: null,
        itemName: null,
        promptsId:null,
        promptsName:null,
        name:null,
        spiderDomain: null,
        spiderUrl: null,
        listDiv: null,
        pageDiv: null,
        status:  "0",
        spiderStatus:null,
        taskTime: null,
        savePath: null,
        spiderAuto: null,
        description: null,
        typeId: null,
        typeName: null,
        orderId: null,
        deleteDiv: null,
        saveDiv: null,
        takeRole: null,
        genStyle: null,
        titleDiv:null,
        pushTimeDiv:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 转换分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //分类选择框
    addSelect(value){
      this.form.typeName = value.label;

      console.log(this.typeName)
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采集配置";
      /** 查询来源下拉框列表 */
      spiderItemSelect().then(response => {
        this.itemOptions = response.data;
      });
      /** 查询生成模型下拉框列表 */
      PromptsSelect().then(response => {
        this.promptsOptions = response.data;
      });

      spiderClassSelect().then(response => {
        this.spiderClassOptions = response.data;
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDiySpider(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采集配置";
      });
      /** 查询来源下拉框列表 */
      spiderItemSelect().then(response => {
        this.itemOptions = response.data;
      });
      /** 查询生成模型下拉框列表 */
      PromptsSelect().then(response => {
        this.promptsOptions = response.data;
      });

      spiderClassSelect().then(response => {
        this.spiderClassOptions = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      var itemId =  this.$refs.optionItemRef.selected.value;
      var itemName =  this.$refs.optionItemRef.selected.label;
      var promptsId =  this.$refs.optionPromtsRef.selected.value;



      var promptsName =  this.$refs.optionPromtsRef.selected.label;
      this.form.itemId = itemId;
      this.form.itemName = itemName;
      this.form.promptsId = promptsId;

      this.form.promptsName = promptsName;


      console.log(this.form);

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            console.log(this.form)
            updateDiySpider(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDiySpider(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });


    },

    /**采集按钮操作**/
    handleSpider(row){
      const ids = row.id || this.ids;
      this.$set(row, 'spiderLoading', true);
      this.piLiangSpiderLoading = true;
      this.$modal.confirm('确定开始采集"' + ids + '"的数据项？').then(function() {

        return toSpider(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("采集任务提交成功");
        this.$set(row, 'spiderLoading', false);
        this.piLiangSpiderLoading = false;
      }).catch(() => {});
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采集配置编号为"' + ids + '"的数据项？').then(function() {
        return delDiySpider(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('article/diySpider/export', {
        ...this.queryParams
      }, `diySpider_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
